package com.ehouse.adapters;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.ResourceCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.ehouse.MainActivity;
import com.ehouse.R;
import com.ehouse.connection.ConnectionService;
import com.ehouse.connection.ConnectionService.IConnectionResponseListener;
import com.ehouse.database.IrrigationTable;

public class IrrigationItemAdapter extends ResourceCursorAdapter{
	private int layout;
	
	
	public IrrigationItemAdapter (Context context, int layout, Cursor c, int flags){
		super(context, layout, c, flags);
		this.layout = layout;
	}

	    @Override
	    public View newView(Context context, Cursor cur, ViewGroup parent) {
	        LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        return li.inflate(layout, parent, false);
	    }

	    @Override
	    public void bindView(View view, final Context context, Cursor cursor) {
	    	boolean state = (cursor.getInt(cursor.getColumnIndex(IrrigationTable.COLUMN_STATE)) == 1);
	    	
            ToggleButton switchButtonView = (ToggleButton)view.findViewById(R.id.rowButton);
            
            
            
            
            switchButtonView.setChecked(state);
            
            switchButtonView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    			
    			public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) {
    				
    				MainActivity.serviceRef.switchSensor("Irrigation", "", isChecked, new ConnectionService.IConnectionResponseListener() {
    					
    					public void responseReceived(Object data, boolean success) {
    						if(success){
    							
    							MainActivity.serviceRef.getLights(new IConnectionResponseListener() {
    								
    								public void responseReceived(Object data, boolean success) {
    									if(!success){
    										Toast.makeText(context,
    												R.string.connection_error, Toast.LENGTH_LONG)
    												.show();
    		
    									}
    										
    								}
    							});
    						}else{
    							Toast.makeText(context,
    									R.string.connection_error, Toast.LENGTH_LONG)
    									.show();

    						}
    					}
    				});
    			}
    		});
	    }
}
